package com.zdj.data.net;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public abstract class RetrofitUtils {

    //服务器路径
    private static final String API_SERVER = "http://test.sucai.xingzhijishu.com/api2/";
    /**
     * 本机服务地址 <br/>
     * 作者 ：zdj <br/>
     * created at 16-11-26 下午9:52
     */
    public static final String BASE_URL_LOCAL = "http://192.168.0.106:8080/rs/";
    
    private static final String TAG = "RetrofitUtils";

    private static Retrofit mRetrofit;
    private static OkHttpClient mOkHttpClient;

    /**
     * 获取Retrofit对象
     *
     * @return
     */
    protected static Retrofit getRetrofit(Context context) {

        if (null == mRetrofit) {

            if (null == mOkHttpClient) {
                mOkHttpClient = OkHttp3Utils.getOkHttpClient(context);
            }
            mRetrofit = new Retrofit.Builder()
//                    .baseUrl(BASE_URL_LOCAL)
                    .baseUrl(API_SERVER)
                    .addConverterFactory(GsonConverterFactory.create(initGson()))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(mOkHttpClient)
                    .build();

        }

        return mRetrofit;
    }



    private static Gson initGson() {
        return new GsonBuilder()
                .registerTypeAdapter(int.class,
                        (JsonDeserializer<Integer>) (json, typeOfT, context) -> {
                            try {
                                return json.getAsInt();
                            } catch (NumberFormatException e) {
                                return -1;
                            }
                        })
                .create();
    }

}